package com.enjoyor.soa.traffic.util.helper;
//

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JaxbHelper<T> {
    public JaxbHelper() {
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshal(Class<T> clazz, InputStream is) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller un = context.createUnmarshaller();
        return (T) un.unmarshal(is);
    }

    public static <T> T unmarshal(Class<T> clazz, File file) throws JAXBException, FileNotFoundException {
        return unmarshal(clazz, (InputStream) (new FileInputStream(file)));
    }

    public static void marshal(Object element, OutputStream os) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(element.getClass());
        Marshaller m = jc.createMarshaller();
        m.setProperty("jaxb.encoding", "gb2312");
        m.marshal(element, os);
    }

    public static void marshal(Object element, File output) throws FileNotFoundException, JAXBException {
        marshal(element, (OutputStream) (new FileOutputStream(output)));
    }

    public static String marshal(Object element) throws JAXBException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        marshal(element, (OutputStream) os);
        byte[] bystr = os.toByteArray();
        String str = "";

        try {
            str = new String(bystr, "gb2312");
        } catch (UnsupportedEncodingException var5) {
            var5.printStackTrace();
        }

        StringBuffer sb = new StringBuffer(
                str.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""));
        return sb.toString();
    }
}
